import os
import yaml
import urllib3

urllib3.disable_warnings()

CURRENT_PATH = os.path.dirname(os.path.abspath(__file__))


def load_config(config_path) -> dict:
    if not os.path.exists(config_path):
        raise FileNotFoundError(f"配置文件不存在: {config_path}")
    with open(config_path, "r", encoding="utf-8") as f:
        cfg = yaml.safe_load(f)
    return cfg


# 加载配置文件
try:
    CONFIG = load_config(os.path.join(CURRENT_PATH, "config.yml"))
except:
    CONFIG = load_config(os.path.join(CURRENT_PATH, "config.template.yml"))
# 是否开启debug模式
DEBUG = CONFIG.get("debug", False)

DATABASE_CONFIG = CONFIG.get("database", {})
# 读取数据库环境变量
if DATABASE_CONFIG.get("use_env"):
    database_type = os.environ.get("DATABASE_TYPE", 'mysql')
    username = os.environ.get("DATABASE_USERNAME", 'root')
    password = os.environ.get("DATABASE_PASSWORD", 'root')
    db_address = os.environ.get("DATABASE_ADDRESS", '127.0.0.1:3306')
    DATABASE_CONFIG["type"] = database_type
    DATABASE_CONFIG["username"] = username
    DATABASE_CONFIG["password"] = password
    DATABASE_CONFIG["address"] = db_address

# 判断数据库类型
DATABASE_TYPE = DATABASE_CONFIG["type"]
if DATABASE_TYPE == "mysql":
    DATABASE_TYPE = "mysql+pymysql"
elif DATABASE_TYPE == "postgresql":
    pass
else:
    raise Exception(f"不支持的数据库类型: {DATABASE_TYPE}")

if "APP_ID" in os.environ and "APP_SECRET" in os.environ:
    SECRET_CONFIG = CONFIG.get("weixin", {})
    SECRET_CONFIG["app_id"] = os.environ.get("APP_ID", '')
    SECRET_CONFIG["app_secret"] = os.environ.get("APP_SECRET", '')
    CONFIG["weixin"] = SECRET_CONFIG

# 腾讯云对象储存初始化
from qcloud_cos import CosConfig
from qcloud_cos import CosS3Client

COS_CONFIG = CONFIG.get("qcloud_cos", {})
if COS_CONFIG.get("use_env"):
    secret_id = os.environ.get("COS_SECRET_ID", '')
    secret_key = os.environ.get("COS_SECRET_KEY", '')
    region = os.environ.get("COS_Region", 'ap-guangzhou')
    bucket = os.environ.get("COS_Bucket", '')
    COS_CONFIG["secret_id"] = secret_id
    COS_CONFIG["secret_key"] = secret_key
    COS_CONFIG["region"] = region
    COS_CONFIG["bucket"] = bucket

COS_Bucket = COS_CONFIG["bucket"]
cos_config = CosConfig(
    Region=COS_CONFIG["region"],
    SecretId=COS_CONFIG["secret_id"],
    SecretKey=COS_CONFIG["secret_key"],
)
cos_client = CosS3Client(cos_config)
sts_config = {
    'url': 'https://sts.tencentcloudapi.com/',
    'domain': 'sts.tencentcloudapi.com',
    'duration_seconds': 1800,
    'secret_id': COS_CONFIG["secret_id"],
    'secret_key': COS_CONFIG["secret_key"],
    'bucket': COS_CONFIG["bucket"],
    'region': COS_CONFIG["region"],
    'allow_prefix': ['files/*'],
    'allow_actions': [
        # 简单上传
        'name/cos:PutObject',
        'name/cos:PostObject',
        # 分片上传
        'name/cos:InitiateMultipartUpload',
        'name/cos:ListMultipartUploads',
        'name/cos:ListParts',
        'name/cos:UploadPart',
        'name/cos:CompleteMultipartUpload'
    ],
}

# 二维码失效时间
QR_CODE_EXPIRATION_MINUTES = 5


# redis配置
REDIS_CONFIG = CONFIG.get("redis", {})
if REDIS_CONFIG.get("use_env"):
    redis_host = os.environ.get("REDIS_HOST", '127.0.0.1')
    redis_port = os.environ.get("REDIS_PORT", 6379)
    redis_db = os.environ.get("REDIS_DB", 0)
    REDIS_CONFIG["host"] = redis_host
    REDIS_CONFIG["port"] = redis_port
    REDIS_CONFIG["db"] = redis_db



